package com.example.spring.test;

import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

public class LockTest2 {
    private Lock lock = new ReentrantLock();

    public static void main(String[] args) {
        final LockTest2 test = new LockTest2();

        new Thread(){
            public void run(){
                test.insert(Thread.currentThread());
            }
        }.start();

        new Thread(){
            public void run(){
                test.insert(Thread.currentThread());
            }
        }.start();

        new Thread(){
            public void run(){
                test.insert(Thread.currentThread());
            }
        }.start();
    }

    public void insert(Thread thread){
//        lock.lock();
//        try {
//            System.out.println(thread.getName() + "得到了锁");
//            for (int i = 0; i < 3; i++) {
//                System.out.println("ThreadName=" + Thread.currentThread().getName() + (" " + (i + 1)));
//            }
//        } catch (Exception e) {
//        } finally {
//            System.out.println(thread.getName() + "释放了锁");
//            lock.unlock();
//        }

        if(lock.tryLock()) {
            try {
                System.out.println(thread.getName()+"得到了锁");
                for (int i = 0; i < 3; i++) {
                    System.out.println("ThreadName=" + Thread.currentThread().getName() + (" " + (i + 1)));
                }
            } catch (Exception e) {
            }finally {
                System.out.println(thread.getName()+"释放了锁");
                lock.unlock();
            }
        } else {
            System.out.println(thread.getName()+"获取锁失败");
        }
    }
}

